package com.cn.web.controller.EM.partRegt;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cn.bean.vo.EM.partRegt.BarkPar;
import com.cn.mapper.dao.db5.EM.entrust.EntrustOutDao;
import com.cn.mapper.dao.db5.EM.partRegt.PartSingleInfoDao;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@CrossOrigin
@RestController
@Transactional
@RequestMapping("/PartSingleInfo")
public class PartSingleInfoController {
    private final PartSingleInfoDao partSingleInfoDao;


    @Autowired(required = false)
    public PartSingleInfoController(PartSingleInfoDao partSingleInfoDao) {
        this.partSingleInfoDao = partSingleInfoDao;
    }
    // 所有需要返回的字段列表（按你的描述补充完整）
    private static final List<String> ALL_FIELDS = Arrays.asList(
            "InitDiameter", "allowManualScrap", "allowManualScrapName", "amount", "b_e_table", "b_m_table",
            "batch_num", "circulationState", "circulationStateName", "circulation_state", "cjr", "cjsj",
            "closeStatus", "color", "componentID", "consumableCategory", "consumableCategoryName",
            "consumption_quantity", "creationTime", "currentStatus", "dateType", "default_ps_id",
            "demarcate_num", "diameter", "e_actual_b_date", "e_actual_e_date", "e_actual_work_hour",
            "e_ref_state", "e_remark", "ecsName", "eid", "equipmentId", "equipmentStructureId",
            "equipment_structure_id", "formMainTable", "grindStandard", "grindToleranceLower",
            "grindToleranceUpper", "grind_quantity", "group_code", "hardnessStandard", "height", "id",
            "init_cone_height", "init_cone_lenght", "init_outside_diameter", "init_roughness",
            "innerHoleStandard", "inputType", "isdel", "lJGrindingNumber", "lJGrindingTimes",
            "latest_ps_id", "length", "lock", "lockName", "lockTable", "material", "materialCode",
            "materialStatus", "materialStatusName", "material_code", "material_state", "model", "modelName",
            "model_id", "nonWorkingFaceOuterDiameterStandard", "partSingleID", "part_id", "processCode",
            "processName", "process_id", "pscQuantity", "pscid", "qr_code", "quantity", "rack_entity_id",
            "rack_num", "register_num", "report_ps_id", "residualGrindingCapacity", "roughnessStandard",
            "roughnessToleranceLower", "roughnessToleranceUpper", "rowNum", "single_id", "sourceMethod",
            "sourcedjID", "special_equipment_id", "special_equipment_name", "specification", "state",
            "structureName", "structure_group_quantity", "structure_quantity", "supplierUniqueCode",
            "supplier_unique_code", "taperHeight", "taperLength", "taperStandard", "thicknessStandard",
            "total", "totalGrindingAmount", "uniqueCode", "unique_code", "unit", "unit_price", "used_num",
            "weight", "width", "workingFaceLength", "workingFaceOuterDiameterStandard"
    );
    private static final Map<String, Set<String>> HEADER_MAP = new HashMap<>();
    static {
        HEADER_MAP.put("unique_code", Set.of("单据编号"));
        HEADER_MAP.put("supplier_unique_code", Set.of("供应商唯一码"));
        HEADER_MAP.put("qr_code", Set.of("速记码"));
        HEADER_MAP.put("init_outside_diameter", Set.of("初始外径(mm)", "初始外径"));
        HEADER_MAP.put("init_roughness", Set.of("初始粗糙度"));
        HEADER_MAP.put("init_cone_height", Set.of("初始锥高(s)", "初始锥高"));
        HEADER_MAP.put("init_cone_lenght", Set.of("初始锥长(mm)", "初始锥长"));
    }
    //导入功能
    @PostMapping("/upload")
    public ResponseEntity<?> getFileInfo(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("code", 400, "message", "文件不能为空"));
            }

            // 解析 Excel 内容
            List<Map<String, String>> dataList = parseExcel(file);

            // 构造响应
            return ResponseEntity.ok(Map.of(
                    "code", 200,
                    "message", "解析成功",
                    "data", dataList
            ));

        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                    "code", 500,
                    "message", "解析失败: " + e.getMessage()
            ));
        }
    }

    // 核心解析方法
    private List<Map<String, String>> parseExcel(MultipartFile file) throws Exception {
        List<Map<String, String>> result = new ArrayList<>();

        try (Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet.getPhysicalNumberOfRows() < 1) {
                throw new RuntimeException("Excel 无有效数据");
            }

            // 解析表头
            Row headerRow = sheet.getRow(0);
            Map<Integer, String> columnMapping = new HashMap<>();
            for (Cell cell : headerRow) {
                String cellValue = cell.getStringCellValue().trim();
                HEADER_MAP.forEach((field, headers) -> {
                    if (headers.contains(cellValue)) {
                        columnMapping.put(cell.getColumnIndex(), field);
                    }
                });
            }

            // 解析数据行
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                Map<String, String> rowData = new HashMap<>();

                // 初始化默认值
                ALL_FIELDS.forEach(field -> rowData.put(field, ""));

                // 设置特殊默认值
                rowData.put("material_state", "0");
                rowData.put("circulation_state", "0");

                // 填充 Excel 解析的数据
                if (row != null) {
                    for (Cell cell : row) {
                        int colIndex = cell.getColumnIndex();
                        String fieldName = columnMapping.get(colIndex);
                        if (fieldName != null) {
                            rowData.put(fieldName, getCellStringValue(cell));
                        }
                    }
                }

                result.add(rowData);
            }
        }

        return result;
    }

    // 获取单元格字符串值
    private String getCellStringValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING: return cell.getStringCellValue().trim();
            case NUMERIC: return String.format("%.0f", cell.getNumericCellValue());
            default: return "";
        }

    }


    @RequestMapping("/insert")
    @ResponseBody
    public BarkPar insert(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonObject:aaaaaaaaaaaaaaa" + jsonObject);


        return partSingleInfoDao.insert(String.valueOf(jsonObject));

    }

    @RequestMapping("/getSing")
    @ResponseBody
    public String getSing(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonObject:aaaaaaaaaaaaaaa" + jsonObject);
        return partSingleInfoDao.getSing(String.valueOf(jsonObject));
    }

    @RequestMapping("/getList")
    @ResponseBody
    public String getList(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonObject:aaaaaaaaaaaaaaa" + jsonObject);
        String list = partSingleInfoDao.getList(String.valueOf(jsonObject));
        System.out.println("xxxxxxxxxxxxxx:" + list);
        return list;
    }

    @RequestMapping("/getRack")
    @ResponseBody
    public String getRack(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonObject:eeeeeeee" + jsonObject);
        String list = partSingleInfoDao.getRack(String.valueOf(jsonObject));
        System.out.println("xxxxxxxxaaxxxxxx:" + list);
        return list;
    }

    @RequestMapping("/getInfo")
    @ResponseBody
    public String getInfo(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonObject:ccccccccccc" + jsonObject);
        String list = partSingleInfoDao.getInfo(String.valueOf(jsonObject));
        System.out.println("assxxxxxxxxxx:" + list);
        return list;
    }

    @RequestMapping("/stateUp")
    @ResponseBody
    public BarkPar stateUp(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonObject:ccccccccccc" + jsonObject);
        return partSingleInfoDao.stateUp(String.valueOf(jsonObject));
    }
    @RequestMapping("/supplier")
    @ResponseBody
    public String supplier(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonObject:ccccccccccc" + jsonObject);
        String list = partSingleInfoDao.supplier(String.valueOf(jsonObject));
        System.out.println("assxxxxxxxxxx:" + list);
        return list;
    }
    @RequestMapping("/getModel")
    @ResponseBody
    public String getEquipment(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonObject:ccccccccccc" + jsonObject);
        String list = partSingleInfoDao.getModel(String.valueOf(jsonObject));
        System.out.println("assxxxxxxxxxx:" + list);
        return list;
    }
    @RequestMapping("/getEquipmentList")
    @ResponseBody
    public String getEquipmentList(@RequestBody JSONObject jsonObject) {
        System.out.println("jsonObject:ccccccccccc" + jsonObject);
        String list = partSingleInfoDao.getEquipmentList(String.valueOf(jsonObject));
        System.out.println("assxxxxxxxxxx:" + list);
        return list;
    }
}
